<!--
 * @Author: zhangguowei 974599791@qq.com
 * @Date: 2022-08-31 15:00:43
 * @LastEditors: zhangguowei 974599791@qq.com
 * @LastEditTime: 2022-09-13 16:02:54
 * @Description: 通用table封装
-->
<script lang="ts" setup>
import { defineProps, VNode, withDefaults, h, onMounted } from "vue";
interface Column {
  label?: string;
  prop?: string;
  width?: string | number;
  minWidth?: string | number;
  type?: "index" | "selection";
  align?: "left" | "center" | "right";
  render?: (h: any, row: any, column: any, $index: number) => VNode;
  slot?: string;
}
const props = withDefaults(
  defineProps<{
    // 渲染表格的数据
    tableData: any[];
    // 列选项
    column: Column[];
    getData?: () => any; // 获取表格数据
    initGetData?: boolean; // 是否初始化表格数据
  }>(),
  { tableData: undefined }
);
// 最终渲染到页面的data
let finalData = props.tableData;

onMounted(() => {
  if (props.initGetData && props.getData) {
    props.getData().then((res) => {
      finalData = res;
    });
  } else {
    finalData = props.tableData;
  }
});
</script>
<template>
  <el-table :data="finalData" v-bind="$attrs" style="width: 100%">
    <el-table-column
      v-for="(item, index) in column"
      :key="index"
      :type="item.type"
      :prop="item.prop"
      :label="item.label"
      :width="item.width"
      :min-width="item.minWidth"
      :align="item.align"
    >
      <!-- 插槽转发 -->
      <template #default="{ row, column, $index }"
        ><slot
          v-if="item.slot"
          :row="row"
          :column="column"
          :index="$index"
        ></slot>
        <component
          v-else-if="item.render"
          :is="item.render(h, row, column, $index)"
        ></component>
      </template>
    </el-table-column>
  </el-table>
</template>



<style>
</style>
